define(function(require, exports, module) {

  var Backbone = require('backbone');
  var $ = require('jquery');
  var _ = require('underscore');
  var jsonview = require('jsonview');

  function main() {
    var $app = $('<div id="app">');
    $('#main').html($app);


    //promise1
    get('/hy5b/auto/jsonp.js')
      .then((res) => {
        console.log(res)
      })
      .catch(error => {
        console.error(error)
      })

    //promise2
    var p = new Promise(function (resolve, reject) {
      console.log('start new Promise...');
      resolve(123);
    });

    p.then(multiply)
     .then(add)
     .then(multiply)
     .then(add)
     .then(function (result) {
        console.log('Got value: ' + result);
    });
  }

  function get(url) {
    return request(url).then(function(res) {
      // console.log(res)
      return res;
    })
  }

  function request(url, data) {
    let fetchParams = {
      method: 'GET',
      headers: {},
      credentials: 'same-origin'
    }

    if (data) {
      fetchParams.body = JSON.stringify(data)
    }

    return new Promise((resolve, reject) => {
      fetch(url, fetchParams)
        .then(res => {
          res = res.json()
          return resolve(res)
        })
        .catch(res => {
          //可以被promise.catch捕获
          return reject(res)
        })
    })
  }

  // 0.5秒后返回input*input的计算结果:
  function multiply(input) {
    return new Promise(function (resolve, reject) {
      console.log('calculating ' + input + ' x ' + input + '...');
      setTimeout(resolve, 500, input * input);
    });
  }

  // 0.5秒后返回input+input的计算结果:
  function add(input) {
    return new Promise(function (resolve, reject) {
      console.log('calculating ' + input + ' + ' + input + '...');
      setTimeout(resolve, 500, input + input);
    });
  }

  return main;
})
